<?php


namespace App\Services\Huanxin;


use App\Services\Configs\DefaultService;

class BaseService
{
    protected $url = null; //接口路径
    protected $app_name = null; //应用名称
    protected $org_name = null; //应用ID
    protected $client_id = null; //开发者ID
    protected $client_secret = null; //开发者密钥
    protected $grant_type = 'client_credentials'; //授权类型

    public function __construct()
    {
        $config = $this->getConfig(DefaultService::HUANXIN_IM);
        if (strrchr($config['url'], '/') !== '/') {
            $this->url = $config['url'] . '/';
        } else {
            $this->url = $config['url'];
        }
        $this->app_name = $config['app_name'];
        $this->org_name = $config['org_name'];
        $this->client_id = $config['client_id'];
        $this->client_secret = $config['client_secret'];
    }

    /**
     * 获取配置信息
     * @param $key 键
     * @return mixed
     * @throws \Exception
     */
    private function getConfig($key)
    {
        $config = new DefaultService();
        $data = $config->first($key);
        if (!$data) {
            throw new \Exception('找不到配置 ' . $key);
        }
        return $data;
    }

    /**
     * 获取令牌
     * @return string
     */
    protected function getToken()
    {
        $options = array(
            "grant_type" => $this->grant_type,
            "client_id" => $this->client_id,
            "client_secret" => $this->client_secret,
        );
        $body = json_encode($options);
        $url = $this->url . 'token';
        $tokenResult = postCurl($url, $body, $header = array());
        return "Authorization:Bearer " . $tokenResult['access_token'];
    }
}
